﻿using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using vBridge.Win32;

namespace vBridge.Wpf
{
    public class WpfMessageHook : IMessageHook, IDisposable // TODO: IDisposable
    {
        private WindowProcedure _procedure;
        private readonly HwndSource _winSource;
        

        public WpfMessageHook(Visual visual)
        {
            _winSource = PresentationSource.FromVisual(visual) as HwndSource;
                if (_winSource == null) throw new ArgumentException("Couldn't find the visual.");
            _winSource.AddHook(Hook);
        }

        public void SetProcedure(WindowProcedure procedure)
        {
            _procedure = procedure;
        }

        private IntPtr Hook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, ref Boolean handled)
        {
            return _procedure(hwnd, msg, wParam, lParam, ref handled);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(Boolean disposing)
        {
            if (disposing)
                _winSource.RemoveHook(Hook);
        }
    }
}